import 'package:alipay_kit/alipay_kit.dart';
import 'package:fate_blind_box/ui/user/matchMaker/maker_manager.dart';
import 'package:fate_blind_box/ui/user/matchMaker/payFailDialog.dart';
import 'package:fate_blind_box/ui/user/matchMaker/paySucessDialog.dart';
import 'package:fate_blind_box/ui/user/profile.dart';
import 'package:fate_blind_box/utils/common_widget.dart';
import 'package:fate_blind_box/utils/page.dart';
import 'package:fate_blind_box/utils/provider.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../../main222.dart';
import '../../../network/Api.dart';
import '../../../theme/theme_color.dart';
import '../../../utils/loading.dart';
import '../Settings/logoutSendCodeDilog.dart';
import 'package:fluwx/fluwx.dart' as fluwx;

import '../authentication/authentication.dart';
import '../institution/companyPodfile.dart';
import '../institution/institution.dart';
import '../institution/registerinstitution.dart';

// class otherMakerUI extends StatelessWidget {
//   final String title;
//   const otherMakerUI(this.title, {Key? key}) : super(key: key);
//
//   @override
//   Widget build(BuildContext context) {
//     return otherMakerUIWidget(title);
//   }
// }

class otherMakerUIWidget extends StatefulWidget {
  final String title;
  final String typeTitle;
  final bool isUpdate;
  const otherMakerUIWidget(this.title, this.typeTitle, {Key? key,this.isUpdate=false})
      : super(key: key);

  @override
  State<otherMakerUIWidget> createState() => otherMakerUIWidgetState();
}

class otherMakerUIWidgetState extends State<otherMakerUIWidget> {
  String money = '';
  late List _listData = [];
  late List _listDataBuss = [];
  int license = -1;
  int isRealAuth = -1;

  @override
  void initState() {
    super.initState();

    switch (widget.title) {
      case '热心红娘':
        money = '99';
        break;
      case '银牌红娘':
        money = '999';
        break;
      case '金牌红娘':
        money = '2999';
        break;
      case '至尊红娘':
        money = '5999';
        break;
    }

    _listData = [
      {
        'img': 'images/ic_fuliM.png',
        'title': '福利',
        "sub":
            '1.${widget.title}权益长期有效（需要每年审核）\n2.推荐粉丝，享受现金推广奖励\n3.粉丝推荐粉丝，享受积分推广奖励\n4.在红娘列表展示，平台公开发布活动，活动有推送功能（推送功能限制次数）',
        'height': 165.0
      },
      // {'img':'images/ic_fensiM.png','title':'粉丝数量',"sub":'拥有50名粉丝','button':'去邀请','height':80.0},
      // {'img':'images/ic_shiming.png','title':'实名认证',"sub":'','button':'去认证','height':60.0},
      {
        'img': 'images/ic_shenqingM.png',
        'title': '申请条件',
        "sub": '${widget.title}认证费$money元/年',
        'button': '去支付',
        'height': 80.0
      }
    ];

    _listDataBuss = [
      {
        'img': 'images/ic_fuliM.png',
        'title': '福利',
        "sub":
            '1.${widget.title}权益长期有效（需要每年审核）\n2.推荐粉丝，享受现金推广奖励\n3.粉丝推荐粉丝，享受积分推广奖励\n4.在吃喝玩乐及单身驿站展示，平台公开发布活动，活动有推送功能（推送功能限制次数）',
        'height': 165.0
      },
      // {'img':'images/ic_fensiM.png','title':'粉丝数量',"sub":'拥有50名粉丝','button':'去邀请','height':80.0},
      {
        'img': 'images/ic_fensiM.png',
        'title': '营业执照',
        "sub": '',
        'button': '去上传',
        'height': 50.0
      },
      {
        'img': 'images/ic_shiming.png',
        'title': '实名认证',
        "sub": '',
        'button': '去认证',
        'height': 50.0
      },
      {
        'img': 'images/ic_shenqingM.png',
        'title': '申请条件',
        "sub": '${widget.title}认证费$money元/年',
        'button': '去支付',
        'height': 80.0
      }
    ];

    _getFansNumberAndAgencyData();
  }

  //查询营业执照和实名认证信息
  void _getFansNumberAndAgencyData() {
    loading(() async {
      final res = await Api.getInstance().checkAgency();
      if (res['code'] == 0) {
        setState(() {
          license = res['data']['license'];
          isRealAuth = res['data']['isRealAuth'];
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;
    return AppWidget.navTitleBar(
      bgColor: const Color(0xFFF9F9F9),
      title: widget.title,
      childWidget: Column(
        children: [
          Container(
            height: size.height - 190,
            child: ListView.builder(
              itemBuilder: (_, index) {
                return widget.typeTitle == '个人红娘'
                    ? _buildItems(_listData?[index], index)
                    : _buildItems(_listDataBuss?[index], index);
              },
              itemCount: widget.typeTitle == '个人红娘'
                  ? _listData.length
                  : _listDataBuss.length,
            ),
          ),
          Expanded(child: Container()),
          Align(
            alignment: Alignment.center,
            child: Container(
                color: Colors.white,
                margin: const EdgeInsets.fromLTRB(0, 0, 0, 0),
                height: 84,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    GestureDetector(
                      onTap: () {
                        if (widget.typeTitle == '个人红娘') {
                          _payType(context, size.width, 1);
                        } else if (widget.typeTitle == '商家红娘') {
                          if (license <= 0) {
                            toast('请先上传营业执照');
                            return;
                          } else if (isRealAuth <= 0) {
                            toast('请先进行实名认证');
                            return;
                          } else {
                            _payType(context, size.width, 3);
                          }
                        }
                      },
                      child: Container(
                        alignment: Alignment.center,
                        margin: const EdgeInsets.fromLTRB(10, 20, 10, 0),
                        padding: const EdgeInsets.symmetric(vertical: 10),
                        height: 45,
                        width: size.width - 80,
                        decoration: ShapeDecoration(
                          shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(22.5)),
                          color: const Color(0xFF7F69D9),
                        ),
                        child: const Text(
                          '确认申请红娘',
                          style: TextStyle(color: Colors.white, fontSize: 16),
                        ),
                      ),
                    ),
                  ],
                )),
          ),
        ],
      ),
    );
  }

  @override
  _buildItems(Map map, int index) {
    double width = MediaQuery.of(context).size.width;
    return GestureDetector(
        child: Container(
      height: map['height'],
      margin: const EdgeInsets.fromLTRB(15, 10, 15, 0),
      decoration: ShapeDecoration(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(5),
        ),
        color: Colors.white,
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Expanded(
            child: Container(
              padding: const EdgeInsets.symmetric(vertical: 0, horizontal: 14),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text.rich(
                    TextSpan(
                      style: const TextStyle(
                          fontSize: 16, fontWeight: FontWeight.bold),
                      children: [
                        WidgetSpan(
                          child: Image.asset(
                            map['img'],
                            width: 16,
                            height: 16,
                          ),
                        ),
                        TextSpan(
                          text: '  ' + map["title"],
                        ),
                      ],
                    ),
                  ),
                  map["sub"].toString().isNotEmpty
                      ? const SizedBox(
                          height: 10,
                        )
                      : const SizedBox(
                          height: 0,
                        ),
                  map["sub"].toString().isNotEmpty
                      ? Text(
                          map["sub"] ?? "",
                          style: TextStyle(
                            color: ThemeColor.checkNormalColor,
                            fontSize: 14,
                          ),
                        )
                      : const SizedBox(),
                ],
              ),
            ),
          ),
          GestureDetector(
            onTap: () async {
              print('ccc $index ${widget.typeTitle}');
              if (widget.typeTitle == '个人红娘') {
                _payType(context, width, index);
              } else if (widget.typeTitle == '商家红娘') {
                if (index == 1 && license <= 0) {
                  _onTapAgency(index);
                } else if (index == 2 && isRealAuth <= 0) {
                  Navigator.of(context)
                      .push(MaterialPageRoute(
                          builder: (builder) => AuthenticationUI()))
                      .then((value) => _getFansNumberAndAgencyData());
                } else if (index == 3) {
                  if (license <= 0) {
                    toast('请先上传营业执照');
                    return;
                  } else if (isRealAuth <= 0) {
                    toast('请先进行实名认证');
                    return;
                  } else {
                    _payType(context, width, index);
                  }
                }
              }
            },
            child: index != 0
                ? Container(
                    height: 32,
                    margin: const EdgeInsets.only(right: 8),
                    decoration: ShapeDecoration(
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(20),
                        ),
                        color: widget.typeTitle == '个人红娘'
                            ? ThemeColor.appColor
                            : (index == 1
                                ? (license <= 0
                                    ? ThemeColor.appColor
                                    : const Color(0xFFF8F8F8))
                                : (index == 2
                                    ? (isRealAuth <= 0
                                        ? ThemeColor.appColor
                                        : const Color(0xFFF8F8F8))
                                    : ThemeColor.appColor))),
                    alignment: Alignment.center,
                    padding: const EdgeInsets.symmetric(horizontal: 12),
                    child: widget.typeTitle == '个人红娘'
                        ? Text(
                            map['button'] ?? '',
                            style: const TextStyle(
                                color: Colors.white, fontSize: 14),
                          )
                        : Text(
                            index == 1
                                ? (license <= 0 ? '去上传' : '已完成')
                                : (index == 2
                                    ? (isRealAuth <= 0 ? '去认证' : '已完成')
                                    : '去支付'),
                            style: TextStyle(
                                color: index == 1
                                    ? (license <= 0
                                        ? Colors.white
                                        : const Color(0xFFAAAAAA))
                                    : (index == 2
                                        ? (isRealAuth <= 0
                                            ? Colors.white
                                            : const Color(0xFFAAAAAA))
                                        : Colors.white),
                                fontSize: 14),
                          ))
                : Container(),
          ),
        ],
      ),
    ));
  }

  //上传营业执照
  _onTapAgency(int index) {
    // Navigate.toPage(registerInstitionUI('ggggg'));
    Navigator.of(context)
        .push(
            MaterialPageRoute(builder: (builder) => registerInstitionUI('nnn')))
        .then((value) => _getFansNumberAndAgencyData());
  }

  Future<void> _payType(context, double width, int index) async {
    showModalBottomSheet(
      context: context,
      builder: (BuildContext context) {
        return Container(
            color: Colors.white,
            // height: 220.0,
            height: 150.0,
            child: Container(
                alignment: Alignment.center,
                child: Column(
                  children: [
                    // GestureDetector(
                    //     onTap: () {
                    //       _onTap(index, '支付宝');
                    //       Navigator.pop(context);
                    //     },
                    //     child: Container(
                    //       alignment: Alignment.center,
                    //       width: width,
                    //       height: 55,
                    //       color: Colors.white,
                    //       child: const Text('支付宝'),
                    //     )
                    // ),
                    // Divider(color: ThemeColor.sendMsgColor, height: 1,),
                    GestureDetector(
                        onTap: () {
                          _onTap(index, '微信');
                          Navigator.pop(context);
                        },
                        child: Container(
                          alignment: Alignment.center,
                          width: width,
                          height: 60,
                          color: Colors.white,
                          child: const Text('微信'),
                        )),
                    Divider(
                      color: ThemeColor.sendMsgColor,
                      thickness: 7,
                      height: 1,
                    ),
                    GestureDetector(
                        onTap: () {
                          Navigator.pop(context);
                        },
                        child: Container(
                          alignment: Alignment.center,
                          width: width,
                          height: 55,
                          color: Colors.white,
                          child: const Text('取消'),
                        ))
                  ],
                )));
      },
    );
  }

  _onTap(int index, String payType) {
    print('yyy $index');
    // if(index == 1){
    print('支付');
    String googId = '';
    switch (widget.title) {
      case '热心红娘':
        googId = '830b4ca24b1511ee9e6d7cd30ae45ca4';
        break;
      case '银牌红娘':
        googId = '87b797c04b1511ee9e6d7cd30ae45ca4';
        break;
      case '金牌红娘':
        googId = '8faf2bbd4b1511ee9e6d7cd30ae45ca4';
        break;
      case '至尊红娘':
        googId = '933a4b464b1511ee9e6d7cd30ae45ca4';
        break;
    }
    int type = 0;
    switch (widget.typeTitle) {
      case '个人红娘':
        type = 1;
        break;
      case '商家红娘':
        type = 2;
        break;
    }
    if (payType == '支付宝') {
      _payoutByAliPay(googId, type);
      // toast('支付宝暂不可用~');
    } else {
      _payoutByWechat(context, googId, type);
    }
    // } else if(index == 2) {
    //
    // } else {
    //   // paySucDialog.showPayDialog(context);
    //   // payFaiDialog.showPayDialog(context);
    // }
  }

  /// 支付宝支付
  _payoutByAliPay(String googId, int type) {
    loading(() async {
      final resType = await Api.getInstance().makerType(Provider.memberId);
      if (resType['code'] == 0) {
        int makerType = resType['data']['matchType'];
        final res;
        if (makerType>0&&widget.isUpdate) {
          res = await Api.getInstance().urgradeMakerByAli(googId, makerType);
        } else {
          res = await Api.getInstance().applyMakerByWechat(googId, type);
        }

        print(res['data']['data']['payPath']);
        final payInfo = res['data']['data']['payPath'];
        AlipayKitPlatform.instance.pay(
          orderInfo: payInfo,
          dynamicLaunch: true,
        );
        AlipayKitPlatform.instance.payResp().listen((event) {
          print('vvvv $event');
          if (event.isSuccessful) {
            _paySuccess(type);
          } else if (event.isCancelled) {
            toast('取消支付~');
          } else {
            toast(event.memo.toString());
          }
        });
      }
    });
  }

  /// 微信支付
  _payoutByWechat(BuildContext context, String googId, int type) async {
    loading(() async {
      final resType = await Api.getInstance().makerType(Provider.memberId);
      if (resType['code'] == 0) {
        int makerType = resType['data']['matchType'];
        final res;
        if (makerType > 0&&widget.isUpdate) {
          res = await Api.getInstance().upgardeMakerByWechat(googId, makerType);
        } else {
          res = await Api.getInstance().payoutByApplyMaker(googId, type);
        }
        if (res['code'] == 0 &&
            res['data'] != null &&
            res['data']['signature'] != null) {
          final payInfo = res['data']['signature'];
          if (kIsWeb) {
            // final jsCtx = js.context;
            // jsCtx['wePayCallback'] = _wePayCallback;
            // jsCtx.callMethod(
            //     "onBridgeReady",
            //     [
            //       payInfo['appId'],
            //       payInfo['timestamp'].toString(),
            //       payInfo['nonce'],
            //       payInfo['pack'],
            //       "MD5",
            //       payInfo['signature']
            //     ]
            // );
          } else {
            fluwx.payWithWeChat(
                appId: payInfo['appId'],
                partnerId: payInfo['partnerId'],
                prepayId: payInfo['prepayId'],
                packageValue: payInfo['pack'],
                nonceStr: payInfo['nonce'],
                timeStamp: payInfo['timestamp'],
                sign: payInfo['signature']);
            fluwx.weChatResponseEventHandler.listen((event) {
              if (event.isSuccessful) {
                // toast("支付成功");
                // Navigator.of(context).push(MaterialPageRoute(builder: (builder) => const MakerManagerPage()));
                _paySuccess(type);
              } else {
                print('vvvv ${event.errStr}  ${event.errCode}');
                if (event.errCode == -2) {
                  toast("用户取消支付了~");
                } else {
                  toast(event.errStr.toString());
                }
              }
            });
          }
        } else {
          toast(res['msg']);
        }
      } else {
        toast(resType['msg']);
      }
    });
  }

  void _paySuccess(int type) {
    if (type == 1) {
      Navigator.of(navKey.currentState!.overlay!.context).pushAndRemoveUntil(
          MaterialPageRoute(builder: (context) => const MakerManagerPage('1')),
          (route) => route == null);
    } else {
      Navigator.of(navKey.currentState!.overlay!.context).pushAndRemoveUntil(
          MaterialPageRoute(builder: (context) => institutionUi('1')),
          (route) => route == null);
    }
  }
}
